import React from 'react';
import { Card, Button, Table, Space, Modal, message, TableProps, Cascader, Tabs } from 'antd';
import type { TabsProps } from 'antd';
import { useParams } from 'react-router-dom';
import _ from 'lodash';
import { type FormPanelObject, InputType } from 'lfun-bg-comp';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaEthicRecordsSrv } from '@/service/teacher';
import { PUNISH_REASON, PUNISH_TYPE } from '@/constant/teachOptions';
import { isPermissionOperate } from '@/component/permission-button';

const SkillQual: React.FC<{ isEditPanel?: boolean }> = ({ isEditPanel = true }) => {
  const columns2: TableProps['columns'] = [
    {
      title: '处分类别',
      dataIndex: 'disciplinary_category',
      key: 'disciplinary_category',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(PUNISH_TYPE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '处分发生时间',
      dataIndex: 'disciplinary_occurrence_date',
      key: 'disciplinary_occurrence_date',
    },
    {
      title: '处分日期',
      dataIndex: 'disciplinary_date',
      key: 'disciplinary_date',
    },
    {
      title: '处分原因',
      dataIndex: 'disciplinary_reason',
      key: 'disciplinary_reason',
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const list2 = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '处分类别',
          name: 'disciplinary_category',
          key: 'disciplinary_category',
          required: true,
          inputType: InputType.select,
          renderOption: PUNISH_TYPE,
        },
        {
          label: '处分原因',
          name: 'disciplinary_reason',
          key: 'disciplinary_reason',
          required: true,
          inputType: InputType.select,
          renderOption: PUNISH_REASON,
          disabled: (form: FormPanelObject) => {
            return !form.getFieldValue('disciplinary_category');
          },
        },
        {
          label: '处分发生日期',
          name: 'disciplinary_occurrence_date',
          key: 'disciplinary_occurrence_date',
          required: true,
          inputType: InputType.date,
          disabled: (form: FormPanelObject) => {
            return !form.getFieldValue('disciplinary_category');
          },
        },
        {
          label: '处分记录描述',
          name: 'disciplinary_record_description',
          key: 'disciplinary_record_description',
          span: 24,
          textRange: [0, 200],
          props: {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
          },
          disabled: (form: FormPanelObject) => {
            return !form.getFieldValue('disciplinary_category');
          },
        },
        {
          label: '处分单位名称',
          name: 'disciplinary_institution_name',
          key: 'disciplinary_institution_name',
          textRange: [0, 20],
          disabled: (form: FormPanelObject) => {
            return !form.getFieldValue('disciplinary_category');
          },
        },
        {
          label: '处分日期',
          name: 'disciplinary_date',
          key: 'disciplinary_date',
          required: true,
          inputType: InputType.date,
          disabled: (form: FormPanelObject) => {
            return !form.getFieldValue('disciplinary_category');
          },
        },
        {
          label: '处分撤销日期',
          name: 'disciplinary_revocation_date',
          key: 'disciplinary_revocation_date',
          inputType: InputType.date,
          disabled: (form: FormPanelObject) => {
            return !form.getFieldValue('disciplinary_category');
          },
        },
        {
          label: '处分撤销原因',
          name: 'disciplinary_revocation_reason',
          key: 'disciplinary_revocation_reason',
          span: 24,
          textRange: [0, 200],
          props: {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
          },
          disabled: (form: FormPanelObject) => {
            return !form.getFieldValue('disciplinary_category');
          },
        },
      ],
    },
  ];

  const { id: teacher_id } = useParams();

  const [formValue, setFormValue] = React.useState({});
  const [dataSource, setDataSource] = React.useState([]);
  const [currentRowId, setCurrentRowId] = React.useState(null);
  const [ethic_type, set_ethic_type] = React.useState('punish');

  React.useEffect(() => {
    fetchData();
  }, [ethic_type]);

  const fetchData = async () => {
    const res = await TeaEthicRecordsSrv.list({ teacher_id, ethic_type });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };

  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({});
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    const { data } = await TeaEthicRecordsSrv.detail(record.teacher_ethic_records_id, ethic_type);
    const params = {
      ...data,
      ethics_assessment_conclusion: data.ethics_assessment_conclusion
        ? data.ethics_assessment_conclusion.split(',')
        : [],
      honor_level: data.honor_level ? data.honor_level?.split(',') : [],
      honor_title: data.honor_title ? data.honor_title?.split(',') : [],
      disciplinary_reason: data.disciplinary_reason ? data.disciplinary_reason?.split(',') : [],
      disciplinary_category: data.disciplinary_category ? data.disciplinary_category?.split(',') : [],
    };
    setCurrentRowId(record.teacher_ethic_records_id);
    setFormValue(params);
    setIsEdit(true);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    Modal.confirm({
      title: '删除',
      content: `是否删除师德考核时间: ${record.ethics_assessment_date} 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaEthicRecordsSrv.delete(record.teacher_ethic_records_id, ethic_type);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    const params = {
      ...values,
      teacher_id,
      ethic_type,
    };
    params.ethics_assessment_date = utils.formatTime(values.ethics_assessment_date);
    params.honor_date = utils.formatTime(values.honor_date);
    params.disciplinary_date = utils.formatTime(values.disciplinary_date);
    params.disciplinary_occurrence_date = utils.formatTime(values.disciplinary_occurrence_date);
    params.disciplinary_revocation_date = utils.formatTime(values.disciplinary_revocation_date);
    //params.ethics_assessment_conclusion = params.ethics_assessment_conclusion?.join(',');
    //params.honor_level = params.honor_level?.join(',');
    //params.honor_title = params.honor_title?.join(',');
    //params.disciplinary_reason = params.disciplinary_reason?.join(',');
    //params.disciplinary_category = params.disciplinary_category?.join(',');

    if (isEdit) {
      params.teacher_ethic_records_id = currentRowId;
    }

    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaEthicRecordsSrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      fetchData();
      setCurrentRowId(null);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  return (
    <Card title="处分" bordered={false}>
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns2} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={isEdit ? (isEditPanel ? '处分编辑' : '处分详情') : '处分新增'}
        visible={showFormModel && ethic_type === 'punish'}
        formValue={formValue}
        changeValue={setFormValue}
        formList={list2}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
      />
    </Card>
  );
};

SkillQual.defaultProps = {
  isEditPanel: true,
};

export default SkillQual;
